var t_optionApp=function(optionPages){
	var self=this;
	self.pages=optionPages;
	
	this.init=function(){
		this.renderNav();
		this.renderPages();
		this.behaviors();
		first=$.getUrlVar('page');
		if(typeof(first)=='undefined' || typeof(self.pages[first])=='undefined')for(var first in self.pages) break;
		self.trigger('navigate.to.page',[{'id':first,'context':self}]);
	}
	
	this.trigger=function(eventType,args){
		console.log('Trigger: '+eventType);
		console.log(args);
		
		$('body').trigger(eventType,args);
	}
	
	this.renderNav=function(){
		if($(NAV_ITEM_CONTAINER).length<=0)return;
		for(var idx in self.pages){
			var item=self.pages[idx];
			(function(id,item,self){
				var elem=$('<li id="nav-'+id+'">'+item.navTitle+'</li>');
				elem.appendTo($(NAV_ITEM_CONTAINER));
				elem.bind('click',function(){
					self.trigger('navigate.to.page',[{'id':id,'context':self}]);
				});
				elem.addClass('nav-item');
				elem.data('page',item);
				elem.data('id',id);
			})(idx,item,self)
		}
	}
	
	this.renderPages=function(){
		var cont=$(PAGE_CONTAINER);
		if(cont.length<=0)return;
		for(var idx in self.pages){
			var item=self.pages[idx];
			(function(id,item,self,cont){
				var page=$('<div class="page" id="'+id+'" style="display:none;"></div>');
				$('<h1 id="title-'+idx+'" class="title">'+item.title+'</h1>').appendTo(page);
				page.data('page',item);
				page.data('id',id);
				page.appendTo(cont);
				self.renderFields(item).appendTo(page);
			})(idx,item,self,cont);
		}
		
	}
	
	this.renderFields=function(item){
		var fields=item.options;
		var elem=$('<div class="fields"></div>');
		for(var idx=0; idx<fields.length; idx++){
			var field=fields[idx];
			switch (field.type) {
				case 'radio':
					elem.append(self.renderFieldRadio(field));
					break;
				case 'select':
					elem.append(self.renderFieldSelect(field));
					break;
				case 'checkbox':
					elem.append(self.renderFieldCheckbox(field));
					break;
				case 'nosql':
					elem.append(self.renderFieldNoSql(field));
					break;
			}
		}
		return elem;
	}
	
	this.renderFieldCheckbox=function(field){
		var elem=$('<div class="field radio"></div>');
		var val=$('<div class="fieldInput"></div>');
		if(field.title)elem.append(self.renderFieldLabel(field));
		elem.append(val);
		var options=field['enum'];
		for(var idx in options){
			var optionContainer=$('<label class="optionContainer radio"></label>');
			var option=$('<input type="checkbox" name="'+idx+'" class="config-setting" />');
			var optionLabel=$('<span>'+options[idx]+'</span>');
			optionContainer.append(option);
			optionContainer.append(optionLabel);
			val.append(optionContainer);
			(function(self,elem){
				elem.bind('change',function(){self.trigger('setting.changed',{'id':elem.attr('name'),'value':elem.is(':checked')});});
			})(self,option);
		}
		return elem;
	}
	
	this.renderFieldRadio=function(field){
		var elem=$('<div class="field radio"></div>');
		var val=$('<div class="fieldInput"></div>');
		if(field.title)elem.append(self.renderFieldLabel(field));
		elem.append(val);
		var options=field['enum'];
		for(var idx in options){
			var optionContainer=$('<label class="optionContainer radio"></label>');
			var option=$('<input type="radio" name="'+field.id+'" value="'+idx+'" class="config-setting" />');
			var optionLabel=$('<span>'+options[idx]+'</span>');
			optionContainer.append(option);
			optionContainer.append(optionLabel);
			val.append(optionContainer);
			(function(self,elem){
				option.bind('change',function(){self.trigger('setting.changed',{'id':elem.attr('name'),'value':elem.val()});});
			})(self,option);
		}
		return elem;
	}
	
	this.renderFieldSelect=function(field){
		var elem=$('<div class="field select"></div>');
		var val=$('<div class="fieldInput"></div>');
		if(field.title)elem.append(self.renderFieldLabel(field));
		elem.append(val);
		var options=field['enum'];
		var optionContainer=$('<span class="optionContainer select"></span>');
		var select=$('<select name="'+field.id+'" class="config-setting"></select>');
		for(var idx in options){
			var option=$('<option value="'+idx+'">'+options[idx]+'</option>');
			select.append(option);
		}
		(function(self,elem){
			select.bind('change',function(){self.trigger('setting.changed',{'id':elem.attr('name'),'value':elem.val()});});
		})(self,select);
		val.append(select).appendTo(elem);
		return elem;
	}
	
	this.renderFieldNoSql=function(field){
		var elem=$('<div class="field nosql nohover"></div>');
		var val=$('<div class="fieldInput"></div>');
		var footer=$('<div class="addButton">'+field.addButtonTitle+'</div>');
		if(field.title)elem.append(self.renderFieldLabel(field));
		elem.append(val);

		var hash=api.nosql.list(field.bucket);
		for(var key in hash){
			var row=$('<div class="row"></div>');
			var eKey=$('<span class="key">'+key+' :</span>');
			var eVal=$('<span class="value" onclick="document.location.replace(\''+hash[key]+'\')">'+hash[key]+'</span>');
			var eMenu=$('<ul class="mini-menu"></ul>');
			var eEdit=$('<li>edit</li>');
			var eDelete=$('<li>delete</li>');
			
			(function(context){
				context.e.bind('click',function(){context.self.trigger('nosql.edit',{'bucket':context.bucket,'key':context.key, 'refresh':true});});
			})({self: self, e:eEdit, bucket: field.bucket, key: key});
			
			(function(context){
				context.e.bind('click',function(){context.self.trigger('nosql.delete',{'bucket':context.bucket,'key':context.key, 'refresh':true});});
			})({self: self, e:eDelete, bucket: field.bucket, key: key});
			
			eMenu.append(eEdit, eDelete);
			row.append(eKey, eVal, eMenu);
			row.appendTo(val);
		}

		(function(context){
			footer.bind('click',function(){context.self.trigger('nosql.add',{bucket: context.bucket});}).appendTo(val);
		})({self:self, bucket: field.bucket});
		val.appendTo(elem);
		return elem;
	}
	
	this.renderFieldLabel=function(field){
		var label=$('<span class="fieldLabel">'+field.title+'</span>');
		return label;
	};
	
	this.showDialog=function(style){
		$('#overlay').show();
		var e=$('<div class="dialog"></div>');
		var c=$('<div class="close">X</div>');
		var b=$('<div class="body" />');
		c.appendTo(e);
		b.appendTo(e);
		(function(context){
			c.bind('click',function(){context.self.hideDialog(context.e);});
		})({e:e,self:self});
		console.log(c);
		e.css(style);
		$('body').append(e);
		e.css({top:'50%',left:'50%',margin:'-'+(e.height() / 2)+'px 0 0 -'+(e.width() / 2)+'px', position: 'fixed'});
		return {dialog:e, close:c, body:b};
	};
	
	this.hideDialog=function(elem){
		$(elem).remove();
		$('#overlay').hide();
	}
	
	this.dialogNosqlCreate=function(bucket,title,key_title,val_title,save_title){
		title=typeof(title)!='undefined'?title:'Create New Value Pair';
		key_title=typeof(key_title)!='undefined'?key_title:'Key';
		val_title=typeof(val_title)!='undefined'?val_title:'Value';
		save_title=typeof(save_title)!='undefined'?save_title:'Save';
		
		var dialog=this.showDialog({width: '300px', height: '159px'});
		dialog['heading']=$('<h1>'+title+'</h2>').appendTo(dialog.body);
		
		dialog['form']=$('<div class="form" />').appendTo(dialog.body);
		
			dialog['key_row']=$('<div class="row" />').appendTo(dialog.form);
				dialog['key_label']=$('<label>'+key_title+'</label>').appendTo(dialog.key_row);
				dialog['key_input']=$('<input type="text" />').appendTo(dialog.key_row);

			dialog['val_row']=$('<div class="row" />').appendTo(dialog.form);
				dialog['val_label']=$('<label>'+val_title+'</label>').appendTo(dialog.val_row);
				dialog['val_input']=$('<input type="text" />').appendTo(dialog.val_row);
		
		dialog['buttonbar']=$('<div class="buttonbar" />').appendTo(dialog.body);
			dialog['button_save']=$('<input type="button" value="'+save_title+'" />').appendTo(dialog.buttonbar);
		
		(function(context){
			context.dialog.button_save.bind('click',function(){
				context.self.hideDialog(dialog.dialog);
				if(context.dialog.key_input.val() && context.dialog.val_input.val()){
					api.nosql.set(context.bucket,context.dialog.key_input.val(),context.dialog.val_input.val());
					context.self.refresh();
				}
			});
		})({bucket:bucket,dialog:dialog, self:self});
		
		return dialog;
	};
	
	this.dialogNosqlEdit=function(bucket,key,title,key_title,val_title,save_title){
		title=typeof(title)!='undefined'?title:'Create New Value Pair';
		key_title=typeof(key_title)!='undefined'?key_title:'Key';
		val_title=typeof(val_title)!='undefined'?val_title:'Value';
		save_title=typeof(save_title)!='undefined'?save_title:'Save';
		
		var dialog=this.showDialog({width: '300px', height: '159px'});
		dialog['heading']=$('<h1>'+title+'</h2>').appendTo(dialog.body);
		
		dialog['form']=$('<div class="form" />').appendTo(dialog.body);
		
			dialog['key_row']=$('<div class="row" />').appendTo(dialog.form);
				dialog['key_label']=$('<label>'+key_title+'</label>').appendTo(dialog.key_row);
				dialog['key_input']=$('<input type="text" />').val(key).appendTo(dialog.key_row);

			dialog['val_row']=$('<div class="row" />').appendTo(dialog.form);
				dialog['val_label']=$('<label>'+val_title+'</label>').appendTo(dialog.val_row);
				dialog['val_input']=$('<input type="text" />').val(api.nosql.get(bucket,key)).appendTo(dialog.val_row);
		
		dialog['buttonbar']=$('<div class="buttonbar" />').appendTo(dialog.body);
			dialog['button_save']=$('<input type="button" value="'+save_title+'" />').appendTo(dialog.buttonbar);
		
		(function(context){
			context.dialog.button_save.bind('click',function(){
				context.self.hideDialog(dialog.dialog);
				if(context.dialog.key_input.val() && context.dialog.val_input.val()){
					api.nosql.del(context.bucket,context.key);
					api.nosql.set(context.bucket,context.dialog.key_input.val(),context.dialog.val_input.val());
					context.self.refresh();
				}
			});
		})({bucket:bucket,dialog:dialog, self:self, key:key});
		
		return dialog
	};
	
	this.getCurrentPage=function(){
		var selected=$(NAV_ITEM_CONTAINER+'>.nav-item.selected').filter(':first');
		return selected.data('id');
	};
	
	this.refresh=function(){
		document.location.replace('?page='+self.getCurrentPage()+'&scroll='+$(window).scrollTop());
	};
	
	this.behaviors=function(){
		$('body').bind('navigate.to.page',function(event,args){
			var curpage=$('#'+self.getCurrentPage());
			var nextpage=$('#'+args.id);
			
			var updateSettings=$('.config-setting',nextpage);
			updateSettings.each(function(){
				var $this=$(this);
				var setting=this.name;
				if(typeof(localStorage[setting])!='undefined'){
					$this.set(localStorage[setting]);
				}
			});

			$(NAV_ITEM_CONTAINER+'>.nav-item').removeClass('selected');
			$('#nav-'+args.id).addClass('selected');
			
			
			console.log(self.getCurrentPage());
			curpage.fadeOut(300);
			nextpage.fadeIn(300);
			
		});
		
		$('body').bind('setting.changed',function(event,args){
			localStorage[args.id]=args.value;
		});
		
		$('body').bind('nosql.delete',function(event,args){
			api.nosql.del(args.bucket,args.key);
			document.location.replace('?page='+self.getCurrentPage());
		});
		
		$('body').bind('nosql.add',function(event,args){
			self.dialogNosqlCreate(args.bucket,'New ShortCode','ShortCode','URL','Save Your New ShortCode');
		});
		
		$('body').bind('nosql.edit',function(event,args){
			self.dialogNosqlEdit(args.bucket,args.key,'Edit ShortCode','ShortCode','URL','Save');
		});
		
	}
}

$.fn.set=function(value){
	var getClass=function(obj){
		return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
	}
	this.each(function(){
		switch(getClass(this)){
			case 'HTMLInputElement':
				switch(this.type){
					case 'button':
						console.log('button');
						break;
					case 'checkbox':
						$(this).prop('checked',value=='true');
						break;
					case 'file':
						break;
					case 'image':
						break;
					case 'radio':
						$(this).prop('checked',false).filter("[value="+value+"]").prop('checked',true);
						break;
					case 'reset':
						break;
					case 'submit':
						break;
					case 'password':
					case 'hidden':
					case 'text':
						$(this).val(value);
						break;
				}
				break;
			case 'HTMLSelectElement':
				$(this).val(value);
				break;
		}
	});
};

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});